package com.bencordingley.remotecontrol;

import java.io.IOException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.Toast;

public class PhoneStateReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(final Context context, Intent intent) {
		final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		boolean pauseOutgoing = prefs.getBoolean("pause_outgoing", true);
		boolean pauseIncoming = prefs.getBoolean("pause_incoming", true);
		if (pauseIncoming || pauseOutgoing) {

			Bundle extras = intent.getExtras();
			if (extras != null) {
				String state = extras.getString("state");
				if (state != null && ((pauseOutgoing && state.equals("OFFHOOK")) || (pauseIncoming && state.equals("RINGING")))) {
					final Context c = context;
					new Thread() {
						@Override
						public void run() {
							NetworkClient client = NetworkClient.connect(context);
							if (client != null) {
								try {
									if (client.isRunning() && !client.isPaused()) {
										client.pause();
									}
								} catch (IOException ex) {
									Toast.makeText(c, "Error pausing host", Toast.LENGTH_SHORT);
									ex.printStackTrace();
								}
							}else{
								Toast.makeText(c, "Error connecting to host", Toast.LENGTH_SHORT);
							}
						}
					}.start();
				}
			}

		}
	}
}
